//
//  HMEmoticonKeyboard.swift
//  04-表情键盘
//
//  Created by Admin on 16/9/13.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class HMEmoticonKeyboard: UIView {
    
    /// textView
    weak var textView: UITextView?

    @IBOutlet weak var collectionView: UICollectionView!
    
    @IBOutlet weak var pageControl: UIPageControl!
    
    @IBOutlet weak var toolBar: HMEmoticonToolbar!
    
    class func emoticonKeyboard() -> HMEmoticonKeyboard {
        return Bundle.main.loadNibNamed("HMEmoticonKeyboard", owner: nil, options: nil)?.last as! HMEmoticonKeyboard
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        collectionView.register(HMEmoticonPageCell.self, forCellWithReuseIdentifier: "cell")
        collectionView.dataSource = self
        collectionView.delegate = self
        
        // 设置toolBar代理
        toolBar.delegate = self
        
        // 设置UIPageControl
        pageControl.currentPageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_selected")!)
        pageControl.pageIndicatorTintColor = UIColor(patternImage: UIImage(named: "compose_keyboard_dot_normal")!)
        
        // 测试
        pageControl.numberOfPages = 5
//        pageControl.backgroundColor = UIColor.black
        
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        
        pageControl.isHidden = true
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        
        layout.itemSize = collectionView!.frame.size
        print("self.layout.itemSize = \(layout.itemSize)")
    }
    
    func setPageControl(indexPath: IndexPath) {
        // 设置pageControl的总页数 = 当前表情包的页数
        pageControl.numberOfPages = HMEmoticonManager.shared.packages[indexPath.section].pageEmoticons.count
        
        // 当前页 = 当section的item
        pageControl.currentPage = indexPath.item
        
        // 第0组不显示
        pageControl.isHidden = indexPath.section == 0
    }
}

extension HMEmoticonKeyboard: HMEmoticonToolbarDelegate {
    func didSelectedButton(didSelectedType type: HMEmoticonToolbarType) {
        print("选中了: \(type)")
        // 切换collectionView对应的section
        
        let indexPath = IndexPath(item: 0, section: type.rawValue)
        collectionView.selectItem(at: indexPath, animated: false, scrollPosition: .left)
        
        setPageControl(indexPath: indexPath)
    }
}

extension HMEmoticonKeyboard: UICollectionViewDataSource {
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return HMEmoticonManager.shared.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return HMEmoticonManager.shared.packages[section].pageEmoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        print("indexPath = \(indexPath)")
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! HMEmoticonPageCell
        
        // 设置为cell的代理
        cell.delegate = self
        
        cell.indexPath = indexPath
        cell.pageEmoticons = HMEmoticonManager.shared.packages[indexPath.section].pageEmoticons[indexPath.item]
        
        return cell
    }
}

extension HMEmoticonKeyboard: HMEmoticonPageCellDelegate {
    func emoticonPageCellDidClickDeleteButton() {
        textView?.deleteBackward()
    }
    
    func emoticonPageCell(didSelectedEmoticon emoticon: HMEmoticonModel) {
        textView?.insertEmoticon(emoticon: emoticon)
        
        let indexPath = collectionView.indexPathsForVisibleItems.first!
        if indexPath.section == 0 {
            return
        }
        
        HMEmoticonManager.shared.addFavorate(emoticon: emoticon)
        
        // 刷新最近这组
        var indexSet = IndexSet()
        indexSet.insert(0)
        collectionView.reloadSections(indexSet)
    }
}

extension HMEmoticonKeyboard: UICollectionViewDelegate {
    // 监听colletionView滚动,来动态设置toolBar上的按钮选中
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // 计算中心参照点
        var refPoint = scrollView.center
        refPoint.x += scrollView.contentOffset.x
        // print("center: \(refPoint)")
        
        // 判断哪个cell包含这个参照点
        for cell in collectionView.visibleCells {
            if cell.frame.contains(refPoint) {
                // 显示这个cell所在的组
                let indexPath = collectionView.indexPath(for: cell)!
//                 print("选中: \(indexPath.section) 组")
                
                // 让toolBar选中按钮
                toolBar.switchSelectedButton(withSection: indexPath.section)
                
                setPageControl(indexPath: indexPath)
                
                break
            }
        }
    }
}
